package com.carqueue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carqueue.common.Result;
import com.carqueue.mapper.CarQueueMapper;
import com.carqueue.pojo.CarQueue;
import com.carqueue.pojo.User;
import com.carqueue.service.CarQueueService;
import com.carqueue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class CarQueueServiceImpl extends ServiceImpl<CarQueueMapper, CarQueue>implements CarQueueService {
    @Autowired
    private CarQueueService carQueueService;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public Result<String> join(Map map) {
        String invitationcode = map.get("invitationcode").toString();
        String username = map.get("username").toString();

        LambdaQueryWrapper<CarQueue> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarQueue::getInvitationcode,invitationcode);
        CarQueue queue = carQueueService.getOne(lambdaQueryWrapper);

        if(queue==null){
            return Result.error("此车队不存在！");
        }

        String preTailer = queue.getTailer();

        queue.setTailer(username);
        queue.setNumofcar(queue.getNumofcar()+1);
        carQueueService.updateById(queue);

        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userService.getOne(queryWrapper);
        user.setInvitationcode(invitationcode);
        user.setPrecar(preTailer);
        userService.updateById(user);

        return Result.success("加入车队成功");
    }
}
